package cn.cjxy.controller;

import cn.cjxy.domain.User;
import cn.cjxy.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class UserController {
    //注入mapper对象
    @Autowired
    private UserMapper userMapper;

    /**
     * 查询所有
     * @return
     */
    @RequestMapping("/findAll")
    @ResponseBody//返回json格式数据
    public List<User> findAll(){
        //调用mapper层方法
        List<User> all = userMapper.findAll();
        return all;
    }

    /**
     * 根据id查询
     * @PathVariable 传递路径参数
     * @param id
     * @return
     */
  /*
    get传递参数
   @RequestMapping(value = "/findById",method = RequestMethod.GET) // http://localhost:8080/findById?id=3
    @ResponseBody
    public User findById(Integer id){
        User user = userMapper.findById(id);
        return user;
    }*/
    //传递路径参数
    @RequestMapping(value = "/findById/{id}") // http://localhost:8080/findById/2
    @ResponseBody
    public User findById(@PathVariable("id") Integer id){
        User user = userMapper.findById(id);
        return user;
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteById/{id}")
    @ResponseBody
    public String deleteById(@PathVariable("id") Integer id){
        boolean b = userMapper.deleteById(id);
        if (b){
            return "删除成功！";
        }
        return "删除失败";
    }

    /**
     * 新增
     */
    @PostMapping("/addUser")//post方式发请求
    @ResponseBody//将返回值转成json格式 同时会跳过视图解析器
    public void addUser(@RequestBody User user){//@RequestBody 接收前端传递给后端的json字符串中的数据(请求体中的数据)，此注解就会将json格式对象的数据封装到实体类
        //要传递的user为如下格式
        /**
         * {
         *     "id": 1,
         *     "username": "root",
         *     "password": "admin",
         *     "birthday": "1998-10-09T16:00:00.000+00:00",
         *     "address": "江西南昌"
         *   }
         */
        System.out.println(user);
        userMapper.insert(user);
    }

    /**
     * 修改
     */

    @RequestMapping("/updateUser")
    @ResponseBody
    public void updateUser(@RequestBody User user){
        userMapper.updateUser(user);
    }
}
